package netty.dubboRPC.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import netty.simple.netty.ClientHandler;

import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName NettyClient
 * @Description TODO
 * @Author director吴
 * @Date 2022/5/18 15:18
 * @Version 1.0
 **/
public class NettyClient {


    //创建线程池
    private static ExecutorService excutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());


    private static NettyClientHandler client;

    //使用代理模式获取代理对象
    public Object getBean(final Class<?> serviceClass, final String providerName) {

        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[]{serviceClass}, (proxy, method, args) -> {

                    if (client == null) {
                        initClient();
                    }
                    //设置发给服务器的信息 providerName 协议头； args[0] 客户端时间发送的数据
                    client.setPara(providerName + args[0]);

                    return excutor.submit(client).get();
                });


    }


    private static void initClient(){

        client = new NettyClientHandler();

        EventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();

        bootstrap
                .group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true) //设置不岩石
                .handler(
                        new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();
                                pipeline
                                        .addLast(new StringDecoder())
                                        .addLast(new StringEncoder())
                                        .addLast(client);
                            }
                        }
                );

        try {


            ChannelFuture connect = bootstrap.connect("127.0.0.1", 7000).sync();


        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }






}
